package com.example.kotlin.mvp_simple

import android.os.Bundle
import android.widget.TextView
import com.example.kotlin.R
import com.example.kotlin.utils.Preference
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty


class LoginActivity : BaseActivity<LoginPresenter>() {
    //懒加载委托
//    val model: IModel by lazy {
//        getloginModel()
//    }
    private var name: String by Preference(this, "name", "")
    private var age: Int by Preference(this, "age", 0)
    private var height: Long by Preference(this, "height", 0)
    private var weight: Float by Preference(this, "weight", 0f)
    private var married: Boolean by Preference(this, "married", false)
    private var update_time: String by Preference(this, "update_time", "")

    operator fun TextView.provideDelegate(value: Any?, property: KProperty<*>) = object :
        ReadWriteProperty<Any?, String?> {
        override fun getValue(thisRef: Any?, property: KProperty<*>): String? = text?.toString()
        override fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) {
            text = value
        }
    }
    val textView :TextView by lazy { this.findViewById<TextView>(R.id.textView) }

    // ①


//// ②
//    textView.text = "Hello"
//    println(message)
//
//// ③
//    message = "World"
//    println(textView.text)




    //            定义懒加载委托
//               ↓   ↓
    val data: String by lazy {
        request()
    }

    fun request(): String {
        println("执行网络请求")
        return "网络数据"
    }


    var count: Int = 0

    //              ①  ②
    //              ↓   ↓
    var total: Int by ::count

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        findViewById<TextView>(R.id.textView).apply {
            setOnClickListener {
                presenter.doLogin("123", "123")
            }

        }
        var message: String? by textView
        UniversalDB(SqlDB()).save()
        UniversalDB(GreenDaoDB()).save()
        textView.text = "Hello"
        println(message)
        message = "World"
        println(textView.text)
//
//// ③`
       name="2022年端午节6月5日"

        println(name)
    }

    interface DB {
        fun save()
    }

    class SqlDB() : DB {
        override fun save() {
            println("save to sql")
        }
    }

    class GreenDaoDB() : DB {
        override fun save() {
            println("save to GreenDao")
        }
    }

    //               参数  通过 by 将接口实现委托给 db
//                ↓            ↓
    class UniversalDB(db: DB) : DB by db

}